package cn.wps.sdk.demo.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

public class FileCopyTool {

    private final Activity mContext;
    private final File mFileDir;

    public FileCopyTool(Activity context) {
        mContext = context;
        mFileDir = getFileDir();
    }

    public void copyFromManager(List<Uri> uriList) {
        try {
            for (Uri file : uriList) {
                String fileName = parseFileName(mContext, file);
                String destPath = mFileDir.getAbsolutePath() + File.separator + fileName;
                if (new File(destPath).exists()) {
                    continue;
                }
                InputStream inputStream = mContext.getContentResolver().openInputStream(file);
                FileUtil.copyFile(inputStream, destPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String parseFileName(Activity activity, Uri uri) {
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            return StringUtil.getNamePart(uri.getPath());
        }
        String name = queryDisplayName(activity, uri);
        if (!TextUtils.isEmpty(name)) {
            return name;
        }
        name = queryOtherColumn(activity, uri);
        if (!TextUtils.isEmpty(name)) {
            return name;
        }

        if (TextUtils.isEmpty(name)) {
            String urlPath = uri.getPath();
            String namePart = StringUtil.getNamePart(urlPath);
            String extPart = StringUtil.pathExtension(urlPath);
            if (!TextUtils.isEmpty(namePart) && !TextUtils.isEmpty(extPart)) {
                name = namePart;
            }
        }
        return name;
    }

    private static String queryDisplayName(Activity activity, Uri uri) {
        ContentResolver resolver = activity.getContentResolver();
        Cursor cur = null;
        String name = null;
        try {
            cur = resolver.query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
            if (cur != null && cur.getCount() == 1 && cur.moveToFirst()) {
                final int displayNameIndex = cur.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
                if (displayNameIndex != -1) {
                    String displayName = cur.getString(displayNameIndex);
                    if (!TextUtils.isEmpty(displayName)) {
                        String namePart =StringUtil.getNamePart(displayName);
                        String ext = StringUtil.pathExtension(displayName);
                        if (!TextUtils.isEmpty(namePart) && !TextUtils.isEmpty(ext)) {
                            name = displayName.trim();
                        }
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            if (cur != null) {
                cur.close();
            }
        }
        return name;
    }

    private static String queryOtherColumn(Activity activity, Uri uri) {
        ContentResolver resolver = activity.getContentResolver();
        Cursor cur = null;
        String name = null;
        try {
            cur = resolver.query(uri, null, null, null, null);
            if (cur != null && cur.getCount() == 1 && cur.moveToFirst()) {
                if (TextUtils.isEmpty(name)) {
                    int fileNameIndex = cur.getColumnIndex("file_name");
                    if (fileNameIndex != -1) {
                        String fileName = cur.getString(fileNameIndex);
                        if (!TextUtils.isEmpty(fileName)) {
                            name = fileName;
                        }
                    }
                }
                if (TextUtils.isEmpty(name)) {
                    int dataIndex = cur.getColumnIndex(MediaStore.MediaColumns.DATA);
                    if (dataIndex != -1) {
                        String dataPath = cur.getString(dataIndex);
                        if (!TextUtils.isEmpty(dataPath)) {
                            name = new File(dataPath).getName();
                        }
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            if (cur != null) {
                cur.close();
            }
        }
        return name;
    }

    public List<File> getAllFile() {
        File[] allFile = mFileDir.listFiles();
        assert allFile != null;
        return Arrays.asList(allFile);
    }

    public File getFileDir() {
        File file = mContext.getExternalFilesDir("document");
        if (!file.exists()) {
            boolean result = file.mkdirs();
            if (!result) {
                throw new RuntimeException("create file dir fail");
            }
        }
        return file;
    }
}
